package com.wizz.trade.information.controller;

import com.wizz.trade.common.PageVo;
import com.wizz.trade.information.dto.SvarDto;
import com.wizz.trade.information.dto.page.SvarPageDto;
import com.wizz.trade.information.entity.Svar;
import com.wizz.trade.information.service.SvarService;
import com.wizz.trade.common.ResponseResult;
import com.wizz.trade.common.constant.StatusCode;
import com.wizz.trade.information.vo.SvarVo;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 资料模块/仓库签约品种
 */
@RestController
@RequestMapping("/svar")
public class SvarController {

    @Resource
    private SvarService svarService;

    /**
     * 添加操作
     * @param svarDto
     * @return
     */
    @PostMapping
    @PreAuthorize("hasAuthority('仓储协议、费率登记')")

    public ResponseResult addSvar(@RequestBody SvarDto svarDto) {
        Svar svar = new Svar();
        BeanUtils.copyProperties(svarDto,svar);
        svarService.addSvar(svar);
        return new ResponseResult<>(StatusCode.OK, "添加成功");
    }

    /**
     * 更新（编辑）操作
     * @param svarDto
     * @param id
     * @return
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('仓储协议、费率登记')")

    public ResponseResult updateSvar(@RequestBody SvarDto svarDto, @PathVariable("id") Integer id) {
        Svar svar = new Svar();
        BeanUtils.copyProperties(svarDto,svar);
        svar.setId(id);
        svarService.updateSvar(svar);
        return new ResponseResult<>(StatusCode.OK, "修改成功");
    }

    /**
     * 删除（撤销）操作
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('仓储协议、费率登记')")

    public ResponseResult deleteSvar(@PathVariable("id") Integer id) {
        svarService.deleteSvar(id);
        return new ResponseResult<>(StatusCode.OK, "删除成功");
    }

    /**
     * 分页刷新、条件查询
     * @param svarPageDto
     * @return
     */
    @GetMapping("/page")
    @PreAuthorize("hasAuthority('仓储协议、费率登记')")

    public ResponseResult<PageVo<SvarVo>> list(SvarPageDto svarPageDto){
        PageVo<Svar> rawPage = svarService.getPage(svarPageDto);
        List<Svar> data = rawPage.getData();
        List<SvarVo> dataVo = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            SvarVo  svarVo = new SvarVo();
            BeanUtils.copyProperties(data.get(i), svarVo);
            dataVo.add(svarVo);
        }
        return new ResponseResult<>(StatusCode.OK, new PageVo<>(rawPage.getPages(), rawPage.getTotal(), dataVo));
    }
}
